package com.zhouyang.websocket.websockettest.mapper;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.zhouyang.websocket.websockettest.entity.ItCode;
import com.zhouyang.websocket.websockettest.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.Mapping;

import java.util.List;

/**
 * @Author:ZhouYang
 * @Description:
 * @Date: Created in 2020/7/15 16:32
 * @Modified By：
 */
@Component //交给Spring管理
public class PersonMapper {

    @Autowired
    private MongoTemplate mongoTemplate;


    public void savePerson(Person person) {
        //不设置标明就是以实体类的名称映射Collection
        this.mongoTemplate.save(person);
    }
    public List<Person> queryPersonListByName(String name) {
        Query query = Query.query(Criteria.where("name").is(name));
        return this.mongoTemplate.find(query, Person.class);
    }

    public List<Person> queryPersonListByName(String name,Integer page, Integer rows) {
        Query query = Query.query(Criteria.where("name").is(name)).limit(rows).skip((page - 1) * rows);
        return this.mongoTemplate.find(query, Person.class);
    }

    public UpdateResult update(Person person) {
        Query query = Query.query(Criteria.where("id").is(person.getId()));
        Update update = Update.update("age", person.getAge());
        return this.mongoTemplate.updateFirst(query, update, Person.class);
    }

    public DeleteResult deleteById(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        return this.mongoTemplate.remove(query, Person.class);
    }

    public void saveItCode(ItCode itCode) {
        mongoTemplate.save(itCode);
    }

    public List<ItCode> findItCode() {
       return  mongoTemplate.find(new Query(), ItCode.class);
    }
}
